﻿using System;
using System.Collections.Generic;
using Windows.System.Threading;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Core;
using System.Net.Http;
using System.Threading.Tasks;
using Win8NearMe.Bean;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace Win8NearMe
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class NetworkLayer : Page
    {
        private String URL_SEND_LOCATION = "http://dev.joomlart.com/public/zoosrv/?uname=Thang&long=104.803422&lat=21.048598&new=true";
        private IAsyncAction ThreadPoolSendLocation;
        private List<CFriend> ArrayFriendNearBy;
        private OnFriendNearByListener mListener;
        private HttpClient httpClient;

        public NetworkLayer()
        {
            ArrayFriendNearBy = new List<CFriend>();
            this.InitializeComponent();
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        public void sendLocation(String lon, String lat)
        {
            asynSendLocation(lon, lat);
            //ThreadPoolSendLocation = Windows.System.Threading.ThreadPool.RunAsync(
            //    (source) =>
            //    {
            //        asynSendLocation(lon, lat);
            //    });

            //ThreadPoolSendLocation.Completed = new AsyncActionCompletedHandler(
            //   async (IAsyncAction source, AsyncStatus status) =>
            //   {
            //       await  Dispatcher.RunAsync(
            //            CoreDispatcherPriority.High,
            //            () =>
            //            {
            //               mListener.onFriendNearByListener(ArrayFriendNearBy);
            //            });

            //   });
        }

        private async void asynSendLocation(String lon, String lat)
        {
            try
            {
                Uri resourceUri;
                String url = URL_SEND_LOCATION + "lon = " + lon + "&lat=" + lat;
                url = URL_SEND_LOCATION;
                if (!Uri.TryCreate(url, UriKind.Absolute, out resourceUri))
                {
                    //rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
                    return;
                }

                //Helpers.ScenarioStarted(StartButton, CancelButton);
                //rootPage.NotifyUser("In progress", NotifyType.StatusMessage);

                try
                {
                    httpClient = new HttpClient();
                    HttpResponseMessage response = await httpClient.GetAsync(url);
                    Task<String> rs = Helper.GetTextResult(response);
                    String result = rs.Result;

                    await Dispatcher.RunAsync(
                       CoreDispatcherPriority.High,
                       () =>
                       {
                           Task<List<Person>> task = CParseUtil.parseFriends(result);
                           List<Person> friends = task.Result;
                           if (friends.Count == 0)
                           {

                           }
                           else
                           {
                               mListener.onFriendNearByListener(friends);
                           }

                           //mListener.onResultTest(result);
                       });
                    // await Helpers.DisplayTextResult(response, OutputField);

                    //rootPage.NotifyUser("Completed", NotifyType.StatusMessage);
                }
                catch (HttpRequestException hre)
                {
                    //rootPage.NotifyUser(hre.Message, NotifyType.ErrorMessage);
                    //OutputField.Text = hre.ToString();
                }
                catch (TaskCanceledException)
                {
                    //rootPage.NotifyUser("Request canceled.", NotifyType.ErrorMessage);
                }
                finally
                {
                    // Helpers.ScenarioCompleted(StartButton, CancelButton);
                }



            }
            catch (Exception ex)
            {
                ex.ToString();
            }
        }


        public void setOnFriendNearByListener(OnFriendNearByListener listener)
        {
            mListener = listener;
        }
    }
}
